/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bground.network.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author s6_kustan_e
 */
public class Client implements Runnable {

    Socket socket;
    ObjectInputStream is;
    ObjectOutputStream os;
    boolean active;
    ArrayList<Command> inputBuffer, outputBuffer;
    Thread self;

    Client(Socket accept) throws IOException {
        active = false;
        socket = accept;
        inputBuffer = new ArrayList<Command>();
        outputBuffer = new ArrayList<Command>();

        is = new ObjectInputStream(socket.getInputStream());
        os = new ObjectOutputStream(socket.getOutputStream());

        self = new Thread(this);
        self.start();
    }

    Command ReadCommand() {
        try {
            if (is.available() > 0) {
                try {
                    return (Command) is.readObject();
                } catch (IOException ex) {
                    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    void WriteCommand(Command c) {
        try {
            os.writeObject(c);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void update(long l) {
        active = true;
    }

    public void run() {
        while (true) {

            while (active) {
                while (!outputBuffer.isEmpty()) {
                    WriteCommand(outputBuffer.remove(0));
                }
                Command input = ReadCommand();
                while (input != null) {
                    inputBuffer.add(input);
                    input = ReadCommand();
                }

            }

            active = false;
        }
    }
}
